<template>
  <div>
    <p>expand-row keys: {{ expandRows }}</p>

    <ul>
      <li v-for="item in dataSource">
        {{ item }}
      </li>
    </ul>

    <el-button @click="handleAdd">+ 新增</el-button>

    <XTable
      :data="dataSource"
      :columns="columns"
      v-model:expandedRowKeys="expandRows"
      :defaultButtons="['edit', 'add', 'remove']"
      @expand="handleExpandCallback"
      @add="handleAddChild"
      @remove="handleRemove"
    >
      <template #operation="{ record, index }">
        <ElButton
          size="small"
          type="success"
          plain
          style="margin-left: 12px"
          @click="handleCommit(index)"
        >
          审批
        </ElButton>
      </template>

      <template #expand="{ record, index, indent, expanded }">
        <XRow
          :ref="tableRef(index)"
          :columns="yTableColumns"
          :raw="{
            send: true,
            code: '123',
            name: 'aaa',
            age: 11111,
            prod: true,
          }"
        >
          <template v-slot="{ row, index }">
            <div
              class="row"
              style="display: flex; justify-content: center; padding: 8px 0"
            >
              <div class="col">
                <Checkbox
                  v-model:checked="row.send"
                  :disabled="!btnIsShow('slot', row.__state__)"
                  >发货计划</Checkbox
                >kg 可发货库存：1500kg
                【总量：2500kg，锁定：1200kg，最低安全量：300kg
              </div>

              <div class="gap"></div>
              <div class="col">
                <Checkbox
                  v-model:checked="row.prod"
                  :disabled="!btnIsShow('slot', row.__state__)"
                  >生产计划</Checkbox
                >kg 【最小生产量：300kg】
              </div>
            </div>
          </template>

          <template
            #footer="{ data }"
            v-if="btnIsShow('slot', record.__state__)"
          >
            <div
              style="
                display: flex;
                justify-content: flex-end;
                padding: 18px 0 0 0;
              "
            >
              <el-button
                type="success"
                size="small"
                @click="handleConfirmChild(index)"
                >保存
              </el-button>
              <el-button
                type="danger"
                size="small"
                >删除</el-button
              >
            </div>
          </template>
        </XRow>
      </template>
    </XTable>
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  nextTick,
  onMounted,
  reactive,
  ref,
  getCurrentInstance,
  type Ref,
} from "vue";
import { Checkbox } from "ant-design-vue";
import type { Columns, WithTableSignal, HandleEvent } from "@/components/XRow/";

import XTable, { useTableData, useTableRowState } from "@/components/XTable/";
import XRow, { useTable } from "@/components/XRow/";

interface DataItem {
  key: number;
  name: string;
  creator: string;
  createdAt: string;
}

const { btnIsShow } = useTableRowState();

// x-table operation
const {
  setTableData: setDataSource,
  getTableData: getDataSource,
  add,
  copy,
  remove,
  setState,
} = useTableData<DataItem>();

// y-table operations: getTableData, addTableData
const { tableRef, ...yTable } = useTable();

interface User {
  name: string;
  age: number;
  send: boolean;
  prod: boolean;
  [key: string]: any;
}

// x-table table-data
const dataSource = setDataSource([
  { name: "11", key: 11, creator: "111", createdAt: "1111" },
]);

// x-table Columns
const columns: Columns<DataItem> = [
  {
    title: "Name",
    dataIndex: "name",
    inputType: {
      is: "select",
      options: [
        { label: "aa", value: "aa" },
        { label: "bb", value: "bb" },
        { label: "cc", value: "cc" },
      ],
    },
  },
  {
    title: "Creator",
    dataIndex: "creator",
    inputType: {
      is: "input",
    },
  },
  { title: "Date", dataIndex: "createdAt" },
];

// x-table expand-rows indexes
const expandRows = ref<string[]>([]);

// x-table add row
const handleAdd = () => {
  add({ name: "xx", creator: "xxx", key: 12, createdAt: "xxxx" });
};

const handleRemove = (event: HandleEvent) => {
  // console.log("🚀 ~ handleRemove ~ event:", event);
  remove(event.index);
};

// x-table 展开行事件
const handleExpandCallback = (expanded: boolean, record: DataItem) => {};

// x-table 当前行是否展开
const isExpand = (id: string) => expandRows.value.includes(id);

// x-table add row items
const handleAddChild = ({ index, record }: HandleEvent) => {
  isExpand(record.__id__) || expandRows.value.push(record.__id__);
  nextTick(() => {
    yTable.addTableData(index);
  });
};

const handleCommit = (index: number) => {
  setState(index, "commit");
  yTable.setTableState(index, "commit");
};

// y-table columns
const yTableColumns: Columns<User> = [
  {
    title: "编码",
    dataIndex: "code",
    width: "10%",
  },
  {
    title: "姓名",
    dataIndex: "name",
    width: "10%",
    inputType: {
      is: "input",
    },
  },
  {
    title: "年龄",
    dataIndex: "age",
    width: "10%",
    inputType: {
      is: "select",
      options: [
        { label: 11, value: 11 },
        { label: 22, value: 22 },
        { label: 33, value: 33 },
        { label: 44, value: 44 },
      ],
    },
  },
  {
    title: "操作",
    dataIndex: "operation",
    width: "10%",
  },
];

// y-table confirm envent
const handleConfirmChild = (index: number) => {
  // console.log("🚀 ~ handleConfirmChild ~ data:", data);

  // 1. y-table view 状态
  yTable.setTableState(index, "view");
  // 2. x-table 当前行 view 状态
  setState(index, "view");
  // 3. x-table 收起当前行
  const currentRowId = dataSource.value[index].__id__;
  expandRows.value = expandRows.value.filter((id) => id !== currentRowId);
  // 4. 发送请求
  const yTableData = yTable.getTableData(index);
  // console.log("🚀 ~ handleConfirmChild ~ yTableData:", yTableData);
};
</script>

<style scoped></style>
